package com.example.qjia.ui.activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


import com.example.qjia.Presenters.LoadMessagePresenter;
import com.example.qjia.Presenters.LoadMessagePresenterImp;
import com.example.qjia.R;
import com.example.qjia.adapter.HolidayAdapter;
import com.example.qjia.basic.BaseActivity;
import com.example.qjia.basic.MyApplication;
import com.example.qjia.data.HolidayMessage;
import com.example.qjia.data.romotedata.AbsenceSlip;
import com.example.qjia.ui.ViewInterface.MainViewInterface;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.graphics.drawable.BitmapDrawable;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;

public class MainActivity extends BaseActivity implements View.OnClickListener,MainViewInterface {

    public static final String TAG="MainActivity";
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView holidayRecylerView;
    private FloatingActionButton floatingActionButton;
    private HolidayAdapter holidayAdapter;
    private List<AbsenceSlip> holidayMessageList;
    private LinearLayoutManager layoutManager;
    //private Handler handler=new Handler();
    private LoadMessagePresenter loadMessagePresenter;
    private boolean isLoading;
    private TextView headLeftTitle;
    private TextView headRightTitle;
    private View contentView;
    private PopupWindow m_popupWindow;
    private LinearLayout userMessagely;
    private LinearLayout userSettingly;
    private LinearLayout versionUpdately;
    private LinearLayout userFeedbackly;
    private int currentPage=1;





    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {

        Log.i(TAG, "init: 学生信息 "+ MyApplication.getStudentId());
        swipeRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.swipe_refresh_layout);
        holidayRecylerView=(RecyclerView)findViewById(R.id.holiday_list);
        floatingActionButton=(FloatingActionButton)findViewById(R.id.btn_float_action);
        headLeftTitle=(TextView)findViewById(R.id.headLeftTitle);
        headRightTitle=(TextView)findViewById(R.id.headRightTitle);
        headRightTitle.setOnClickListener(this);
        floatingActionButton.setOnClickListener(this);
        holidayMessageList = new ArrayList<>();
        holidayAdapter = new HolidayAdapter(holidayMessageList,this);
        loadMessagePresenter=new LoadMessagePresenterImp(this);
        contentView = getLayoutInflater().inflate(R.layout.dialog, null,
                true);
        userMessagely=(LinearLayout)contentView.findViewById(R.id.user_message);
        userMessagely.setOnClickListener(this);
        userSettingly=(LinearLayout)contentView.findViewById(R.id.user_setting);
        userSettingly.setOnClickListener(this);
        versionUpdately=(LinearLayout)contentView.findViewById(R.id.version_update);
        versionUpdately.setOnClickListener(this);
        userFeedbackly=(LinearLayout)contentView.findViewById(R.id.user_feed_back);
        userFeedbackly.setOnClickListener(this);

        m_popupWindow = new PopupWindow(contentView, LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, true);

        m_popupWindow.setBackgroundDrawable(new BitmapDrawable());//有了这句才可以点击返回（撤销）按钮dismiss()
        m_popupWindow.setOutsideTouchable(true);
        m_popupWindow.setAnimationStyle(R.style.PopupAnimation);





    }

    @Override
    protected void initView() {

        holidayRecylerView.setItemAnimator(new DefaultItemAnimator());

        swipeRefreshLayout.setColorSchemeResources(R.color.colorTheme);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {                    //刷新
                holidayMessageList.clear();
                loadMessagePresenter.loadMessage();
                currentPage=1;

            }
        });
        layoutManager = new LinearLayoutManager(this);
        holidayRecylerView.setLayoutManager(layoutManager);
        holidayRecylerView.setAdapter(holidayAdapter);
        holidayRecylerView.addOnScrollListener(new RecyclerView.OnScrollListener() {//下拉到底部加载更多
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == holidayAdapter.getItemCount()) {

                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        holidayAdapter.notifyItemRemoved(holidayAdapter.getItemCount());
                        return;
                    }
                    if (!isLoading&&holidayAdapter.getItemCount()>11) {
                        Map<String,String> params =new HashMap<String, String>();
                        params.put("userId",MyApplication.getStudentId()+"");
                        params.put("userType",2+"");
                        params.put("pageNum",++currentPage+"");//下一页
                        params.put("pageSize",11+"");
                            isLoading = true;
                            loadMessagePresenter.loadmoreMessage(params);// 加载更多
                            isLoading = false;


                    }
                }
            }
        });
        initData();
    }




    public void initData() {
        loadMessagePresenter.loadMessage();



    }

    @Override
    public void loadnothing() {
        swipeRefreshLayout.setRefreshing(false);
        //toast("暂时没有假条记录");
    }

    @Override
    public void onClick(View view) {
        int viewId=view.getId();
        Log.w(TAG, "onClick: "+viewId);
        if(viewId==R.id.btn_float_action){
            loadMessagePresenter.toAddholiday();
        }
        if(viewId==R.id.headRightTitle){
            loadMessagePresenter.showSettingDialog(view);
        }
        if(viewId==R.id.user_message){
            loadMessagePresenter.toUserSetting(1);
            if(m_popupWindow.isShowing())m_popupWindow.dismiss();
        }
        if(viewId==R.id.user_setting){
            loadMessagePresenter.toUserSetting(2);
            if(m_popupWindow.isShowing())m_popupWindow.dismiss();

        }
        if(viewId==R.id.version_update){
            loadMessagePresenter.toUserSetting(3);
            if(m_popupWindow.isShowing())m_popupWindow.dismiss();

        }
        if(viewId==R.id.user_feed_back){
            loadMessagePresenter.toUserSetting(4);
            if(m_popupWindow.isShowing())m_popupWindow.dismiss();

        }

    }

    @Override
    public void toUserSettingActivity(int fragmentId){
        Intent intent=new Intent(MainActivity.this,UserSetingActivity.class);
        Bundle params=new Bundle();
        params.putInt("fragmentId",fragmentId);
        intent.putExtras(params);
        startActivity(intent);

    }
    @Override
    public void toAddActivity() {
        Intent intent=new Intent(MainActivity.this,AddHolidayActivity.class);
        startActivity(intent);

    }

    @Override
    public void showSettingDialog(View view) {
        Log.w(TAG, "showSettingDialog: 设置的ID"+view.getId());
        try {

            if (m_popupWindow.isShowing()) {

                m_popupWindow.dismiss();
            }
            m_popupWindow.showAsDropDown(view);


        } catch (Exception e) {
            toast("dialog");
        }


    }

    @Override
    public void loadMessage(List<AbsenceSlip> datalist ) {
        if(holidayMessageList==null){
            holidayMessageList=new ArrayList<>();
        }
        Log.i(TAG, "loadMessage: 数据回来了");
        holidayMessageList.addAll(datalist);
        holidayAdapter.notifyDataSetChanged();

        swipeRefreshLayout.setRefreshing(false);
        holidayAdapter.notifyItemRemoved(holidayAdapter.getItemCount());



    }

    @Override
    protected void onResume() {
        super.onResume();
        swipeRefreshLayout.setRefreshing(true);
        holidayMessageList.clear();
        holidayAdapter.notifyDataSetChanged();
        loadMessagePresenter.loadMessage();

        currentPage=1;
        swipeRefreshLayout.setRefreshing(false);





    }

}
